<script setup lang="ts">
import type { KeyValueProps } from '@/types';

import { ref, useTemplateRef, watch } from 'vue';

import { Icon } from '@/components/core/icon';

import {
  ElButton,
  ElDescriptions,
  ElDescriptionsItem,
  ElInput,
  ElMessage,
} from 'element-plus';
import bus from 'vue3-eventbus';

import { useWebSocketStore } from '@/store/websocket';

defineOptions({
  name: 'WorkConnect',
});
const { hostname } = window.location;
const wsStore = useWebSocketStore();
const socketElRef = useTemplateRef('socketElRef');
const socketHasError = ref(false);
const socketState = ref();
const socketUrl = ref(`ws://${hostname}:11112`);
const EventStore: KeyValueProps = {};
const setupWebSocket = () => {
  wsStore.connect(socketUrl.value);
};

const handleConnect = () => {
  if (!socketUrl.value) {
    ElMessage.error({
      message: '请输入WebSocketUrl地址',
      type: 'error',
    });
    socketHasError.value = true;
    socketElRef.value?.focus();
    setTimeout(() => {
      socketHasError.value = false;
    }, 1000);
    return;
  }
  setupWebSocket();
};
const handleConnectStop = () => {
  wsStore.disconnect();
};

const onOpen = (opened: number) => {
  const key = 'ws-open';
  if (EventStore[key]) return;
  EventStore[key] = true;
  socketState.value = opened;

  delete EventStore[key];
  bus.off(key);
};
bus.on('ws-open', onOpen);

watch(
  () => wsStore.url,
  (val) => {
    if (val) {
      socketUrl.value = val;
      if (socketUrl.value) {
        setupWebSocket();
      }
    }
  },
  { deep: true, immediate: true },
);

watch(
  () => socketState.value,
  (val) => {
    if (val) {
      ElMessage.success({
        message: '连接成功',
      });
    } else {
      ElMessage.error({
        message: '连接断开',
      });
    }
  },
);
</script>

<template>
  <div class="wos-connect">
    <ElDescriptions :column="1" border class="wos-connect-descriptions">
      <ElDescriptionsItem label="WebSocket URL">
        <div :class="[{ error: socketHasError }]" class="input">
          <ElInput
            ref="socketElRef"
            v-model="socketUrl"
            placeholder="请输入WebSocketUrl地址"
            size="small"
          >
            <template #append>
              <Icon
                :color="socketState ? '#f29e39' : '#666'"
                :icon="socketState ? `mdi:lan-connect` : `mdi:lan-disconnect`"
                :title="socketState ? '已连接' : '未连接'"
                class="size-4"
              />
            </template>
          </ElInput>
        </div>
      </ElDescriptionsItem>
    </ElDescriptions>
    <div class="wos-connect__footer">
      <ElButton
        v-if="!socketState"
        size="small"
        type="primary"
        @click="handleConnect()"
      >
        连接
      </ElButton>
      <ElButton v-else size="small" @click="handleConnectStop()">
        断开
      </ElButton>
    </div>
  </div>
</template>
<style lang="scss">
.wos-connect {
  display: flex;
  flex-direction: column;
  gap: 8px;
  justify-content: space-between;
  width: 100%;
  height: 100%;
  padding: 24px;
  color: var(--el-text-color-primary);
  text-shadow: none;

  &-descriptions {
    background-color: var(--wos-box-right-bg);
  }

  .el-input-group__append,
  .el-input__wrapper {
    border-radius: 0;
    box-shadow: none;
  }

  .input {
    &.error {
      animation: input-error-animation 0.2s ease 3;
    }
  }

  &__footer {
    display: flex;
    gap: 8px;
    justify-content: flex-end;
  }
}
</style>
